﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.DirectoryServices;

namespace CheckGUID
{
    public class GuidProcessor
    {

        protected AppDataSet.AppUsersNeedingGuidCheckDataTable m_checkTheseUsersGuidsTable = null;
        protected AppDataSetTableAdapters.AppUsersNeedingGuidCheckTableAdapter m_checkUserGuidAdapter = null;
        protected AppDataSet.ErrorTableDataTable m_errors = new AppDataSet.ErrorTableDataTable();

        public GuidProcessor()
        {
            m_checkUserGuidAdapter = new CheckGUID.AppDataSetTableAdapters.AppUsersNeedingGuidCheckTableAdapter();

        }

        public GuidProcessor(AppDataSet.AppUsersNeedingGuidCheckDataTable dt)
        {
            m_checkTheseUsersGuidsTable = dt;
        }

        public void Process()
        {
            if (null == m_checkTheseUsersGuidsTable || null == m_checkTheseUsersGuidsTable.Rows || m_checkTheseUsersGuidsTable.Rows.Count == 0)
            {
                m_checkTheseUsersGuidsTable = new AppDataSet.AppUsersNeedingGuidCheckDataTable();

                try
                {
                    m_checkUserGuidAdapter.Fill(m_checkTheseUsersGuidsTable);
                }
                catch (Exception ex)
                {
                    m_errors.AddErrorTableRow(ex);
                }
            }

            if (m_checkTheseUsersGuidsTable.Rows.Count == 0)
            {
                return;
            }


        }

        protected String findActiveDirectoryUserBySurname(String searchCriteria)
        {
            DirectoryEntry canwestDomain = new DirectoryEntry("LDAP://DC=ca,DC=canwest,DC=com");
            DirectorySearcher pcSearch = new DirectorySearcher(canwestDomain);
            pcSearch.Filter = "(&(objectClass=User)(sn=" + searchCriteria + "))";
            String resultPath = null;

            try
            {
                SearchResult result = pcSearch.FindOne();

                if (null == result)
                {
                    return null;
                }

                resultPath = result.Path;


            }
            catch (Exception ex)
            {
                m_errors.AddErrorTableRow(ex);
            }

            return resultPath;

        }

        protected String getUserGuid(String entryPath)
        {
            if (String.IsNullOrEmpty(entryPath))
            {
                return null;
            }

            DirectoryEntry adUser = new DirectoryEntry(entryPath);

            if (null == adUser)
            {
                return null;
            }

            return adUser.Guid.ToString();
        }
    
    
    }
}
